import '@/App.scss';
import MyHead from './component/MyHeader';
import useMyRoutes from './hook/useMyRoutes';
import { ReactNode, Suspense, useEffect } from 'react';
import { FloatButton } from 'antd';
import { userLogin } from './request';
import userStore from './store/userStore';
import { requestSourceMap } from './request/myAxios';

function App() {
  //初始化路由、登录
  const routes = useMyRoutes();

  const changeRoute = (r: ReactNode) => {
    init();
    for (const [, source] of requestSourceMap) {
      source.cancel();
    }
    requestSourceMap.clear();
    return r;
  };

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    try {
      if (userStore.isLogin) return;
      const token = localStorage.getItem('token');
      if (!token) throw new Error('没有token');
      const user = await userLogin();
      user && userStore.login(user);
    } catch (error) {
      userStore.logout();
    }
  };

  return (
    <div className={`App`}>
      <MyHead></MyHead>
      <div className='content-container'>
        <Suspense fallback={<h1>page loading...</h1>}>
          {changeRoute(routes)}
        </Suspense>
        <FloatButton.BackTop style={{ bottom: 20, right: 70 }} />
      </div>
    </div>
  );
}

export default App;
